﻿using Minecraft.Config;
using Minecraft.Model;
using Minecraft.Model.ReqResp;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Minecraft.ServerHall.Cmd
{
	/// <summary>
	/// 心跳包
	/// </summary>
	public class HeartData : CommandBase<MinecraftSession, StringRequestInfo>
	{
		public override string Name
		{
			get
			{
				return ProtocolHelper.GetProtocolStr(defCommand);
			}
		}
		private EnumCommand defCommand = EnumCommand.Heart_HeartData;
		public override void ExecuteCommand(MinecraftSession session, StringRequestInfo requestInfo)
		{
			var req = requestInfo.GetRequestObj<HeartDataReq>(session);
			if (req == null)
			{
				return;
			}

			bool isVerify = false; //心跳包是否验证
			if (isVerify)
			{
				if (req.StrEncrypted.IsNullOrWhiteSpace())
				{
					return;
				}
				string deStr = "";
				try
				{
					deStr = EncryptHelper.Decrypt(req.StrEncrypted, "server_heartData");
				}
				catch (FormatException ex)
				{
					session.Logger.Fatal("server_heartData: FormatException  " + ex.Message);
					return;
				}
				catch (Exception ex)
				{
					session.Logger.Fatal("server_heartData: Exception  " + ex.Message);
					return;
				}
				if (deStr.IsNullOrWhiteSpace())
				{
					return;
				}
				var strs = deStr.Split(new String[] { " " }, StringSplitOptions.None);
				if (strs.Count() != 2)
				{
					return;
				}
				if (strs[0] != JsonConfig.Value.HeartData.ReqSecretKey)
				{
					return;
				}
				if (!long.TryParse(strs[1], out long ticks))
				{
					return;
				}
				if (ticks <= 0)
				{
					return;
				}
				DateTime time = new DateTime(ticks);
				var subMinuts = Convert.ToInt32(Math.Abs((DateTimeOffset.Now - time).TotalMinutes));
				var HeartDataReqTimeFrameInt = JsonConfig.Value.HeartData.ReqTimeFrame;
				if (subMinuts > HeartDataReqTimeFrameInt)
				{
					return;
				}
			}

			//心跳包合法
			session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Success, Msg = "心跳包" });
		}
	}
}
